package com.nexgo.payment.trans.setting.terminalkey.bccdownkey;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;

import com.nexgo.oaf.apiv3.SdkResult;
import com.nexgo.oaf.apiv3.device.pinpad.AlgorithmModeEnum;
import com.nexgo.oaf.apiv3.device.pinpad.PinPad;
import com.nexgo.payment.api.ApiDeviceEngine;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.trans.setting.terminalkey.downkey.DownloadKeyContract;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by wzp on 2018/1/9.
 */

public class BccDownloadKeyPresenter implements BccDownloadKeyContract.Presenter{
    private final Context mContext;
    private final BccDownloadKeyContract.View mView;
    private final DataSource mRepository;
    private final Handler mHandler;
    private BCCLoadTmk mBCCLoadTmk;
    private Logger log;

    public BccDownloadKeyPresenter(@NonNull Context context, @NonNull BccDownloadKeyContract.View view, @NonNull DataSource repository) {
        mContext = context.getApplicationContext();
        mView = checkNotNull(view);
        mRepository = checkNotNull(repository);
        mHandler = new Handler(Looper.getMainLooper());
        mBCCLoadTmk = new BCCLoadTmk(mRepository);
        mView.setPresenter(this);
        log = LoggerFactory.getLogger("BccDownloadKeyPresenter");
    }
    @Override
    public void start() {
        onStartImportKey();
    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {
        mBCCLoadTmk.cancelLoadKey();
    }

    @Override
    public void onStartImportKey() {
        new Thread(() -> {
            // 交行下秘钥主机超时时间为10秒
            int retCode = mBCCLoadTmk.loadKeyByCom(0, 10);
            switch (retCode){
                case SdkResult.Success:
                    postMainThread(() -> mView.showSuccessful());
                    break;
                default:
                    postMainThread(() -> mView.showFail());
                    break;
            }
        }).start();
    }

    protected void postMainThread(Runnable runnable) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            runnable.run();
        } else {
            mHandler.post(runnable);
        }
    }
}
